<template>
  <div ref="wrapper" class="wrapper">
    <div>
      <slot></slot>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'

export default {
  name: "Scroll",
  props: {
    probeType: {
      type: Number,
      default: 0
    },
    click: {
      type: Boolean,
      default: true
    },
    pullUpLoad: {
      type: Boolean,
      default: false
    },
    data: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      scroll: null
    }
  },
  computed: {
    // 计算属性  数据变动立马进行判断y的值 然后重新刷新计算页面高度 
    // 防止页面假死
    // 计算属性的参数
    scrollY() {
      return this.scroll.y
    }
  },
  mounted() {
    setTimeout(this._initScroll, 100)
  },
  methods: {
    _initScroll() {

      // 1.创建BetterScroll
      this.scroll = new BScroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click,
        pullUpLoad: this.pullUpLoad
      })

      // 2.监听事件滚动的操作 监听组件是不是可以进行滚动
      if (this.probeType === 2 || this.probeType === 3) {
        this.scroll.on('scroll', position => {
          this.$emit('scroll', position)
        })
      }

      // 3.上拉加载
      if (this.pullUpLoad) {
        this.scroll.on('pullingUp', () => {
          this.$emit('pullingUp')
        })
      }

    },
    // 重新计算子组件的高度 来进行重新计算最新的高度
    refresh() {
      this.scroll && this.scroll.refresh && this.scroll.refresh()
    },

    finishPullUp() {
      this.scroll && this.scroll.finishPullUp && this.scroll.finishPullUp()
    },

    scrollTo(x, y, time = 100) {
      this.scroll && this.scroll.scrollTo && this.scroll.scrollTo(x, y, time)
    },

  },
  watch: {
    data() {
      // 数据发生变动 立马执行重新刷新的操作
      setTimeout(this.refresh, 100)
    }
  }
}
</script>

<style scoped>
.wrapper {
  overflow: hidden;
}
</style>
